博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react apollo_Apollo GraphQL:如何使用React和Node Js构建全栈应用
阅读量:2523 次
发布时间:2019-05-11

本文共 10068 字,大约阅读时间需要 33 分钟。

react apollo

Apollo Client is a complete state management library for JavaScript apps. It's a powerful tool since it can be used on both the back end and front end side.

Apollo Client是用于JavaScript应用程序的完整状态管理库。 这是一个强大的工具,因为它既可以在后端使用,也可以在前端使用。

In this tutorial, we will use it on the front end and back end by building an Apollo GraphQL Server with Node JS. Then we will consume the data on the client-side using React JS.

在本教程中,我们将通过使用Node JS构建Apollo GraphQL服务器在前端和后端使用它。 然后,我们将使用React JS在客户端使用数据。

If you're new to GraphQl, might help you. Otherwise, let's get started.

如果您不熟悉GraphQl, 可能会为您提供帮助。 否则,让我们开始吧。

使用Apollo,Node和GraphQl构建服务器 (Building the server with Apollo, Node, and GraphQl)

In this guide, I will use the Github API to have data to show, and that operation will be done by the GraphQl server built with Apollo and Node JS.

在本指南中,我将使用Github API来显示数据,该操作将由使用Apollo和Node JS构建的GraphQl服务器完成。

To make this happen, we need to run the following command on the terminal to set up a new Node JS project:

为此,我们需要在终端上运行以下命令来设置新的Node JS项目:

yarn init

Once the set up is done, we can now install the necessary packages by running this command:

设置完成后,我们现在可以通过运行以下命令来安装必要的软件包:

yarn add apollo-server graphql axios

Great, we now have all we need to build a server. So first let's create a new file app.js in the root which will be the entry point of our server.

太好了,我们现在拥有构建服务器所需的一切。 因此,首先让我们在根目录中创建一个新文件app.js ,它将是服务器的入口点。

Next, we need to define a Graphql schema that mirrors the way our data should look.

接下来,我们需要定义一个Graphql模式,以反映我们的数据外观。

GraphQl模式 (GraphQl Schema)

A schema describes the shape of your data graph. It defines a set of types with fields that are populated from your back-end data stores. So, let's add a new schema in the app.js file.

模式描述数据图的形状。 它定义了一组类型,这些类型的字段是从后端数据存储中填充的。 因此,让我们在app.js文件中添加一个新架构。

  • app.js

    app.js

const { ApolloServer, gql } = require("apollo-server")const axios = require("axios")const typeDefs = gql`  type User {    id: ID    login: String    avatar_url: String  }  type Query {    users: [User]  }`

As you can see we don't use all data provided by the Github API. We just need the id that will be used as a reference key on the React App, the login, and the avatar_url. We also have a query users that returns an array of users.

如您所见,我们并未使用Github API提供的所有数据。 我们只需要将ID用作React App上的参考键,登录名和avatar_url。 我们还有一个查询users ,它返回用户数组。

Now that we have a GraphQL schema, it's time to build the corresponding resolvers to complete the query operation.

现在我们有了GraphQL模式,是时候构建相应的解析器来完成查询操作了。

GraphQl解析器 (GraphQl resolvers)

A resolver is a collection of functions that helps generate a response from a GraphQL query. So, let's add a new resolver in the app.js file.

解析器是有助于从GraphQL查询生成响应的功能的集合。 因此,让我们在app.js文件中添加一个新的解析器。

  • app.js

    app.js

const resolvers = {  Query: {    users: async () => {      try {        const users = await axios.get("https://api.github.com/users")        return users.data.map(({ id, login, avatar_url }) => ({          id,          login,          avatar_url,        }))      } catch (error) {        throw error      }    },  },}

A resolver has to match the appropriate schema by name. Therefore, here users refers to the users query defined in our schema. It's a function that fetches the data from the API with the help of axios and returns as expected the id, the login, and the avatar_url.

解析程序必须按名称匹配适当的架构。 因此,这里的users指的是在我们的架构中定义的users查询。 这个函数可以在axios的帮助下从API提取数据, axios预期返回ID,登录名和avatar_url。

And that operation can take time to complete. That's why async/await is used here to handle it.

该操作可能需要一些时间才能完成。 这就是为什么在这里使用async / await来处理它的原因。

With that, we can now create the Apollo Server in the next section.

这样,我们现在可以在下一部分中创建Apollo服务器。

创建Apollo服务器 (Creating the Apollo Server)

If you remember, in the app.js file, we had imported ApolloServer from the apollo-server package. It's a constructor that receives an object as an argument. And that object must contain the schema and the resolver to be able to create the server.

如果您还记得的话,在app.js文件中,我们已经从apollo-server包中导入了ApolloServer 。 这是一个接收对象作为参数的构造函数。 并且该对象必须包含架构和解析器,才能创建服务器。

So, let's tweak app.js a bit with ApolloServer.

所以,我们修改app.js一点与ApolloServer

  • app.js

    app.js

const server = new ApolloServer({  typeDefs,  resolvers,})//  typeDefs: typeDefs,//  resolvers: resolversserver.listen().then(({ url }) => console.log(`Server ready at ${url}`))

Here, we pass as a parameter an object that holds the schema and the resolver to ApolloServer to create the server and then listens to it. With that in place, we now have a functional server to work with.

在这里,我们将一个持有架构和解析器的对象作为参数传递给ApolloServer以创建服务器,然后监听它。 有了这个,我们现在可以使用功能服务器。

You can already play with it and send queries with the help of GraphQL playground by running this command:

通过运行以下命令,您已经可以使用它并在GraphQL游乐场的帮助下发送查询:

yarn start

You can now preview it on http://localhost:400

您现在可以在http://localhost:400上预览它

  • The complete app.js file

    完整的app.js文件

const { ApolloServer, gql } = require("apollo-server")const axios = require("axios")const typeDefs = gql`  type User {    id: ID    login: String    avatar_url: String  }  type Query {    users: [User]  }`const resolvers = {  Query: {    users: async () => {      try {        const users = await axios.get("https://api.github.com/users")        return users.data.map(({ id, login, avatar_url }) => ({          id,          login,          avatar_url,        }))      } catch (error) {        throw error      }    },  },}const server = new ApolloServer({  typeDefs,  resolvers,})server.listen().then(({ url }) => console.log(`Server ready at ${url}`))

A server alone does not do much. We need to add a start script in the package.json file to, as you guessed, start the server.

单独一个服务器并不能做很多事情。 如您所料,我们需要在package.json文件中添加启动脚本,以启动服务器。

  • package.json

    package.json

// first add nodemon: yarn add nodemon --dev  "scripts": {    "start": "nodemon src/index.js"  }

With that, we have a server to fetch data from the Github API. So now it's time to move to the client-side and consume the data.

这样,我们就有了一个服务器,可以从Github API获取数据。 因此,现在是时候移至客户端并使用数据了。

Let's do it.

我们开始做吧。

使用React构建客户端 (Building the Client-side with React)

The first thing we have to do is create a fresh React App by running the following command in the terminal:

我们要做的第一件事是通过在终端中运行以下命令来创建一个新的React App:

npx create-react-app client-react-apollo

Next, we need to install the Apollo and GraphQl packages:

接下来,我们需要安装Apollo和GraphQl软件包:

yarn add apollo-boost @apollo/react-hooks graphql

Now, we can connect Apollo with our React App by updating the index.js file.

现在,我们可以通过更新index.js文件将Apollo与我们的React App连接起来。

将React连接到Apollo (Connecting React to Apollo)

  • index.js

    index.js

import React from 'react';import ReactDOM from 'react-dom';import ApolloClient from 'apollo-boost'import { ApolloProvider } from '@apollo/react-hooks';import App from './App';import './index.css';import * as serviceWorker from './serviceWorker';const client = new ApolloClient({  uri: 'https://7sgx4.sse.codesandbox.io'})ReactDOM.render(  
, document.getElementById('root'));serviceWorker.unregister();

As you can see, we start by importing ApolloClient and ApolloProvider. The first helps us inform Apollo about which URL to use when fetching data. And if no uri is passed to ApolloClient, it will take the current domain name plus /graphql.

如您所见,我们首先导入ApolloClientApolloProvider 。 第一个帮助我们告知Apollo在获取数据时要使用哪个URL。 如果没有uri传递给ApolloClient ,它将使用当前域名加上/graphql

The second is the Provider which expects to receive the client object to be able to connect Apollo to React.

第二个是希望接收客户端对象以能够将Apollo连接到React的Provider。

That said, we can now create a component that shows the data.

也就是说,我们现在可以创建一个显示数据的组件。

取得资料 (Fetching the data)

  • App.js

    App.js

import React from "react"import { useQuery } from "@apollo/react-hooks"import gql from "graphql-tag"import "./App.css"const GET_USERS = gql`  {    users {      id      login      avatar_url    }  }`

Here, we have a simple GraphQL query that fetches the data. That query will be passed later to useQuery to tell Apollo which data to fetch.

在这里,我们有一个简单的GraphQL查询来获取数据。 该查询将稍后传递给useQuery以告知Apollo要提取哪些数据。

  • App.js

    App.js

const User = ({ user: { login, avatar_url } }) => (  
)

This presentational component will be used to display a user. It receives the data from the App component and displays it.

此演示组件将用于显示用户。 它从App组件接收数据并显示它。

显示数据 (Showing the data)

  • App.js

    App.js

function App() {  const { loading, error, data } = useQuery(GET_USERS)  if (error) return 

Something went wrong!

if (loading) return

Loading...

return (

Github | Users

{data.users.map(user => (
))}
)}export default App

The useQuery hook provided by Apollo receives the GraphQL query and returns three states: the loading, the error, and the data.

Apollo提供的useQuery挂钩接收GraphQL查询并返回三种状态:加载,错误和数据。

If the data are successfully fetched, we pass it to the User component. Otherwise we throw an error.

如果成功获取了数据,我们会将其传递给用户组件。 否则,我们将引发错误。

  • The complete App.js file

    完整的App.js文件

import React from "react"import { useQuery } from "@apollo/react-hooks"import gql from "graphql-tag"import "./App.css"const GET_USERS = gql`  {    users {      id      login      avatar_url    }  }`const User = ({ user: { login, avatar_url } }) => (  
)function App() { const { loading, error, data } = useQuery(GET_USERS) if (error) return

Something went wrong!

if (loading) return

Loading...

return (

Github | Users

{data.users.map(user => (
))}
)}export default App

Great! With that, we are now done building a full-stack Apollo GraphQL app using React and Node JS.

大! 至此,我们现在已经完成了使用React和Node JS构建全栈Apollo GraphQL应用程序的过程。

Preview the Apollo GraphQL Server

在预览Apollo GraphQL服务器

Preview the React App

在预览React App

Find the source code

在找到源代码

You can find other great content like this on

您可以在找到类似的其他精彩内容

Thanks for reading!

谢谢阅读!

翻译自:

react apollo

转载地址:http://ujhwd.baihongyu.com/

你可能感兴趣的文章
PHP与正则表达式 2 :一些修饰符与preg_match_all
查看>>
压八位高精度 高精操作大全
查看>>
进程、线程、协程和GIL(二)
查看>>
dockerfile语法规则
查看>>
模块的导入
查看>>
《Inside C#》笔记(八) 接口
查看>>
kafka介绍
查看>>
java类加载机制及方法调用
查看>>
《大话西游》:我的意中人是一个盖世英雄
查看>>
iOS 清除xcode缓存和生成文件
查看>>
为什么幻灯片画布不居中
查看>>
flask模板应用-javaScript和CSS中jinja2 --
查看>>
react-native 调用原生方法
查看>>
查看Mac系统所有USB设备信息 解决android studio无法识别真机问题
查看>>
20145238 《信息安全系统设计基础》第2周学习总结
查看>>
android 获取日期
查看>>
HDU-1018 BigNumber(斯特林近似)
查看>>
Excel公式——单元格前加固定字符串
查看>>
BZOJ.4738.[清华集训2016]汽水(点分治 分数规划)
查看>>
testNG框架的四种传参方式
查看>>